# yourapp/signals.py
from django.db import models
from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver
from app01.models import IDCDevice, IDCDeviceLog
import datetime

# 创建一个字典来存储原始数据
original_data = {}


@receiver(pre_save, sender=IDCDevice)
def capture_original_data(sender, instance, **kwargs):
    if instance.pk:
        original_data[instance.pk] = sender.objects.get(pk=instance.pk)


@receiver(post_save, sender=IDCDevice)
def log_device_action(sender, instance, created, **kwargs):
    if created:
        action = '创建'
        details = f"{instance.sn} created。"
    else:
        action = '更新'
        if instance.pk in original_data:
            old_data = original_data[instance.pk]
            changes = {}
            for field in sender._meta.fields:
                field_name = field.name
                # 排除自动生成的主键
                if field.primary_key:
                    continue
                old_value = getattr(old_data, field_name)
                new_value = getattr(instance, field_name)
                # 对于 datetime 类型，先转换再比较
                if isinstance(old_value, datetime.datetime):
                    old_value = old_value.strftime('%Y-%m-%d %H:%M:%S')
                if isinstance(new_value, datetime.datetime):
                    new_value = new_value.strftime('%Y-%m-%d %H:%M:%S')
                # 对于 GenericIPAddressField 类型，只有当值发生变化时才记录
                if isinstance(field, models.GenericIPAddressField):
                    if old_value != new_value and (old_value or new_value):
                        changes[field_name] = {
                            'old': old_value,
                            'new': new_value
                        }
                elif old_value != new_value:
                    changes[field_name] = {
                        'old': old_value,
                        'new': new_value
                    }
            if changes:
                details = f"{instance.sn} updated：{changes}"
            else:
                details = f"{instance.sn} 没有实际更改。"
        else:
            details = f"{instance.sn} 更新，但无法确定具体更改。"

    # 记录设备的变化情况
    IDCDeviceLog.objects.create(
        device=instance,
        action=action,
        details=details
    )
